﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Fdd.Aspen.Infrastructure.Data;
using System.Data.Objects;
using System.ComponentModel.DataAnnotations;
using System.ServiceModel.DomainServices.Server;
using System.Diagnostics.Contracts;

namespace WcfRiaServices.Extensions
{
    public class ObjectContextDomainService : DomainService
    {
        private IObjectContext _objectContext;
        

        public void Initialize(
                                IObjectContext objectContext,
                                DomainServiceContext domainServiceContext)
        {
            Contract.Requires(objectContext != null);
            Contract.Requires(domainServiceContext != null);
            Contract.Ensures(_objectContext != null);
            
            _objectContext = objectContext;

            base.Initialize(domainServiceContext);
        }


        protected override bool PersistChangeSet()
        {
            _objectContext.SaveChanges();

            return base.PersistChangeSet();
        }


        public override object Invoke(
                                    InvokeDescription invokeDescription,
                                    out IEnumerable<ValidationResult> validationErrors)
        {
            var result = base.Invoke(invokeDescription, out validationErrors);

            _objectContext.SaveChanges();
            
            return result;
        }


        protected override void Dispose(bool disposing)
        {
            _objectContext.Dispose();

            base.Dispose(disposing);
        }
    }
}
